﻿using System.Collections;

namespace AspNetCore.Host.Hosting
{
    /// <summary>
    /// 对象工厂
    /// </summary>
    public interface IFeatureCollection : IEnumerable<KeyValuePair<Type, object?>>
    {
        TFeature? Get<TFeature>() where TFeature : class;
        void Set<TFeature>(TFeature? instance);
    }

    public class FeatureCollection : IFeatureCollection, IEnumerable<KeyValuePair<Type, object?>>
    {
        private Dictionary<Type, object?> target = new Dictionary<Type, object?>();

        public FeatureCollection()
        {

        }
        public FeatureCollection(IFeatureCollection list)
        {
            foreach (var item in list)
            {
                Set(item);
            }
        }

        public TFeature? Get<TFeature>()
            where TFeature : class
        {
            var key = typeof(TFeature);
            if (target.TryGetValue(key, out object? value))
            {
                return value as TFeature;
            }
            return default;
        }

        public void Set<TFeature>(TFeature? instance)
        {
            target.Add(typeof(TFeature), instance);
        }

        public IEnumerator<KeyValuePair<Type, object?>> GetEnumerator()
        {
            return ((IEnumerable<KeyValuePair<Type, object?>>)target).GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)target).GetEnumerator();
        }
    }

}
